/**
 * manageId = 6
 * 合计（手动拼接 ）= 河东总干渠 + 东干渠
 * 河东总干渠  = 秦渠 + 汉渠 + 马莲渠
 *
 * 只读 ： 盐环定
 *
 * 可分解
 */

import { Component, ElementRef, Input, OnInit, ViewChild, HostListener } from '@angular/core';
import { NzInputDirective, NzMessageService, NzModalService } from 'ng-zorro-antd';
import { UtilService } from '../../../../../core/util/util.service';
import { DispatchPlanService } from '../../../dispatch-plan.service';
import { FetchService } from '../../../../../core/net/fetch.service';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import * as _ from 'lodash';
import { concatMap } from 'rxjs/operators';

const monthHead31 = ['01日', '02日', '03日', '04日', '05日', '06日', '07日', '08日', '09日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日'];

const monthHead30 = ['01日', '02日', '03日', '04日', '05日', '06日', '07日', '08日', '09日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日'];

const XunHash = {
    'F': '上',
    'S': '中',
    'T': '下'
};
@Component({
    selector: 'app-detail-table-qhq',
    templateUrl: './detail-table-qhq.component.html',
    styleUrls: ['./detail-table-qhq.component.scss']
  })
export class DetailTableQhqComponent implements OnInit {
    dataFlag = 1; // 1 上报数据 指标查看 2 数据分解
    scrollConfig =  {
        x: '1200px',
    };
    planData = 0; // 年计划指标
    yearOnYear = 0; // 同比
    planState: "0"; // 计划状态
    planName: string;
    openType: string;
    yearSelection = new Date();
    xunSelection = 'F';

    paramsData = {
        manageId: "4",
        reportId: '5',
        y: '',
        m: '',
        dataType: '',
        dataFlag: '1', // 1为上报数据查询 2为分解数据查询
    };

    monthReportType = 'month';  //  月旬上报类型 月-month 旬-tenDays 冬灌-winter

    monthHead: Array<string> = [];
    monthStatus = '0';
    xunHead = {
        'F': ['01日', '02日', '03日', '04日', '05日', '06日', '07日', '08日', '09日', '10日'],
        'S': ['11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日'],
        'T': ['21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日']
    };
    tableDaysData = []; // 表格val 数据
    relatedTable = []; // 关联表格 盐环定
    keyList = []; // 数据 数值属性 列表
    daysTotalData = []; // 统计表格
    tenDaysStatus = '0'; // 0  未提交 1 已提交 2 已下发
    colNameList = []; // 与接口互动
    dataList = []; // 合计行的所有行
    dqtmList = []; // 大清 & 泰民
    editId: any;
    editCache: { [key: string]: { edit: boolean; data: any } } = {};
    @ViewChild(NzInputDirective, { static: false, read: ElementRef }) inputElement: ElementRef;

    @HostListener('window:click', ['$event'])
    handleClick(e: MouseEvent): void {
        if (this.dataFlag != 2) {
            this.calcTableData();
        }
        if (this.inputElement && e.target['tagName'] !== 'INPUT') {
            Object.keys(this.editCache).forEach(key => {
                this.editCache[key].edit = null;
            });
        }
    }
    constructor(
        private util: UtilService,
        private dispatchService: DispatchPlanService,
        private fetchService: FetchService,
        private message: NzMessageService,
        private routerInfo: ActivatedRoute,
        private modal: NzModalService
    ) {
        this.openType = this.routerInfo.snapshot.queryParams['openType'];
        console.log(JSON.parse(this.routerInfo.snapshot.queryParams['paramsData']));
        this.paramsData = JSON.parse(this.routerInfo.snapshot.queryParams['paramsData']);
        this.initDataParams();
        this.dataFlag = JSON.parse(this.routerInfo.snapshot.queryParams['paramsData']).dataFlag;
        this.planName = JSON.parse(this.routerInfo.snapshot.queryParams['paramsData']).planName;
    }

    ngOnInit() {
        this.getEditableTableData();
    }

    //  初始化时间格式
    initDataParams() {
        if (this.openType === 'add') {
            // 新增状态默认新增下一个时间段的计划
           // this.paramsData = Object.assign(this.paramsData, this.dispatchService.getNextDateInterval());
            if (this.paramsData.dataType) {
               // this.planName = `${this.paramsData.y}年${this.paramsData.m}月${XunHash[this.paramsData.dataType]}旬 用水计划`;
            } else if (this.paramsData.m === 'd') {
               // this.planName = `${this.paramsData.y}年10月20日 ~ ${this.paramsData.y}年11月25日 用水计划`;
            } else {
               // this.planName = `${this.paramsData.y}年${this.paramsData.m}月 用水计划`;
            }
        } else {
            this.paramsData = Object.assign(this.paramsData, JSON.parse(this.routerInfo.snapshot.queryParams['paramsData']));
          //  this.planName = this.routerInfo.snapshot.queryParams['planName'];
        }
        this.monthReportType = this.dispatchService.getMngReportTableType(this.paramsData.m).type;

        if (this.paramsData.m === '4' || this.paramsData.m === '6') {
            this.xunHead['T'] = ['21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日'];
        } else {
            this.xunHead['T'] = ['21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日'];
        }
    }
    // 接口获取数据
    getEditableTableData() {
        Object.keys(this.editCache).forEach(key => {
            this.editCache[key].edit = null;
        });
        this.fetchService.post<any>('plan/wrsReportData/query', this.paramsData).subscribe(res => {
            this.planData = res.planData;
            this.planState = res.state;
            if (this.dataFlag === 2) {
                this.colNameList = res['colNameList'].filter(colName => {
                    return [27, 28, 30, 31].includes(colName.areaId);
                });
            } else {
                this.colNameList = _.cloneDeep(res['colNameList']);
            }
            if (this.openType === 'add') {
                if (Array.isArray(res.valList) && res.valList.length) {
                    if (this.planState === "0") {
                      //  this.message.warning(`${this.planName} 已创建,请编辑`);
                    } else {
                       // this.message.warning(`${this.planName} 已提交,不可编辑`);
                    }
                }
                if (!Array.isArray(res.valList2) || res.valList2.length === 0) {
                    this.message.warning(`盐环定管理处 还未申报计划`);
                }
            }
            this.tenDaysStatus = res['state'];
            const dataParams = {
                type: this.monthReportType,
                m: this.paramsData.m,
                dataType: this.paramsData.dataType,
                period: res['period'],
            };
            const result = this.dispatchService.getTableDate(this.colNameList, res['valList'], dataParams );
            this.tableDaysData = _.cloneDeep(result.tableList);
            this.keyList = _.cloneDeep(result.keyList);
            this.updateEditCache(this.tableDaysData);
            if (res['valList2']) {
                const relateTableResult = this.dispatchService.getTableDate(res['colNameList2'], res['valList2'], dataParams );
                this.relatedTable = _.cloneDeep(relateTableResult.tableList);
            }
            if (this.paramsData.m === '9') {
                this.monthHead = monthHead30;
            } else if (['F', 'S', 'T'].includes(this.paramsData.dataType)) {
                this.monthHead = this.xunHead[this.paramsData.dataType];
            } else if (this.paramsData.m === 'd') {
                const stDate = res['period']['st_date'].split('-');
                const edDate = res['period']['ed_date'].split('-');
                this.planName = `${this.paramsData.y}年${stDate[0]}月${stDate[1]}日 ~ ${this.paramsData.y}年${edDate[0]}月${edDate[1]}日 用水计划`;
                this.monthHead = this.dispatchService.getMngWinterHead(stDate, edDate);
            } else {
                this.monthHead = monthHead31;
            }
            this.scrollConfig.x = (80 * this.monthHead.length + 150) + 'px';
            if (this.paramsData.dataFlag != '2') {
                this.dealTableRow();
                this.calcTableData();
            }

        });
    }

    getYearOnYear(): void {
        const totalObj = this.daysTotalData.find(item => {
            return item.type === 'total';
        });
        if (totalObj) {
            this.yearOnYear = totalObj.water - this.planData;

        }
    }

    // 添加总结行 标记行 河东总干渠
    dealTableRow() {
        this.tableDaysData.forEach(item => {
            if (item.areaId == 27) {
                item.type = "hdzgq";
            }
        });
        const totalObj = {
            type: 'total',
            name: '合计',
        };
        const keysList = Object.keys(this.tableDaysData[0]).filter(key => {
            return key.slice(0, 3) === 'val';
        });
        this.dataList = this.tableDaysData.filter(item => {
            return item.areaId != 27;
        });
        keysList.forEach(key => {
            totalObj[key] = "";
        });
        this.tableDaysData.unshift(totalObj);
    }
    // 计算表格数据
    calcTableData() {
        if (this.dataFlag != 2) {
            if (this.tableDaysData[0]) {
                const keysList = Object.keys(this.tableDaysData[0]).filter(key => {
                    return key.slice(0, 3) === 'val';
                });
                // 河东总干渠  = 秦渠 28 + 汉渠 30 + 马莲渠 31
                const hdzgqList = this.tableDaysData.filter(item => {
                    return  [28, 30, 31].includes(item.areaId);
                });
                this.tableDaysData.forEach(obj => {
                    if (obj.type === 'hdzgq') {
                        keysList.forEach(key => {
                            obj[key] = this.util.sum(this.util.getItemValues(hdzgqList, key, true));
                        });
                    }
                });
                // 合计 = 河东总干渠 27 + 东干渠 32
                const totalList = this.tableDaysData.filter(item => {
                    return  item.areaId == 27 || item.areaId == 32;
                });
                this.tableDaysData.forEach(obj => {
                    if (obj.type === 'total') {
                        keysList.forEach(key => {
                            obj[key] = this.util.sum(this.util.getItemValues(totalList, key, true));
                        });
                    }
                });

            }


            // 计算 统计 表格
            this.daysTotalData = [];
            this.tableDaysData.forEach((optObj, index) => {
                let avgFlow;
                let row = [];
                if (this.monthReportType === 'tenDays') {
                    if (this.paramsData.dataType === 'T') { // 下
                        row = this.dispatchService.getValList(optObj, this.paramsData.m === '5' ? 11 : 10);
                        avgFlow = this.dispatchService.keepTwoDecimalFull((this.util.sum(row) / (this.paramsData.m === '5' ? 11 : 10)));
                    } else {
                        row = this.dispatchService.getValList(optObj, 10);
                        avgFlow = this.dispatchService.keepTwoDecimalFull((this.util.sum(row) / 10));
                    }
                } else if (this.monthReportType === 'month') {
                    row = this.dispatchService.getValList(optObj, this.paramsData.m === '9' ? 30 : 31);
                    avgFlow = this.dispatchService.average(row);
                } else {
                    row = this.dispatchService.getValList(optObj);
                    avgFlow = this.dispatchService.average(row);
                }
                const totalFlow = this.util.sum(row);
                const calResult = {
                    type: "",
                    areaId: optObj.areaId,
                    name: optObj.name,
                    total: this.dispatchService.keepTwoDecimalFull(totalFlow),
                    avg: avgFlow,
                    water: this.dispatchService.getWaterByFlow(totalFlow)
                };
                if (optObj.type === 'total') {
                    calResult.type = 'total';
                }
                this.daysTotalData.push(calResult);
            });
            this.getYearOnYear();
        }
    }

    //  处理接口返回数据格式 获取表格数据
    private dataParse(dataList, valList): Array<any> {
        return dataList.map(item => {
            return _.filter(valList, o => {
                return parseInt(o['areaId'], 10) === parseInt(item['areaId'], 10);
            });
        });
    }

    // 提交 、 保存
    submitEvent(type?) {
        const message = type ? '提交' : '保存';
        this.modal.confirm({
            nzTitle: `确认${message}？`,
            nzContent: '',
            nzOnOk: () => {
                this.calcTableData();
                const params = {
                    manageId: this.paramsData.manageId,
                    reportId: '5',
                    y: this.paramsData.y,
                    m: this.paramsData.m,
                    dataType: this.paramsData.dataType,
                    action: type ? type : "",
                    data: ""
                };
                let tableDataCache = [];
                if (this.dataFlag === 2) {
                    tableDataCache = this.tableDaysData.filter(item => {
                        return item.areaId && item.centerShow === '0';
                    });
                } else {
                    tableDataCache = this.tableDaysData.filter(item => {
                        return item.areaId;
                    });
                }
                if (type === 'manageDivide') {// 数据分解
                    const checkFlag = tableDataCache.some(item => {
                        return Object.keys(item).some(key => {
                            return key.indexOf('val') != -1 && (item[key] === undefined || item[key] === null);
                        });
                    });
                    if (checkFlag) {
                        this.message.warning(`请分解完所有数据再重新提交`);
                        return false;
                    }
                }
                params.data = this.dispatchService.getTableSubmitData(this.monthReportType, tableDataCache);
                this.fetchService.post<any>('plan/wrsReportData/add', params).subscribe(res => {
                    this.message.success(`${message}成功`);
                });
            }
        });
    }

    isEditableTd(id, type?): boolean {
        if (this.openType !== 'view' && type != 'total' && type != 'hdzgq') {
            return id !== 'total' && this.editCache[id].edit;
        } else {
            return false;
        }
    }

    startEdit(id, event: MouseEvent): void {
        event.preventDefault();
        event.stopPropagation();
        if (this.dataFlag === 2) {
            if (['28', '30', '31', 28, 30, 31].includes(id)) {
                this.editCache[id].edit = true;
                this.editId = id;
            }
        } else {
            if (id !== 'total') {
                this.editCache[id].edit = true;
                this.editId = id;
            }
        }
    }

    updateEditCache(data): void {
        data.forEach(item => {
            this.editCache[item.areaId] = {
                edit: false,
                data: { ...item }
            };
        });
    }
}
